<template>
  <div class="container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item v-if="editID">修改商品</el-breadcrumb-item>
      <el-breadcrumb-item v-else>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 10px">
      <!-- 消息提示 -->
      <el-alert
        :title="editID ? '修改商品信息' : '添加商品信息'"
        type="info"
        show-icon
        center
        :closable="false"
      >
      </el-alert>

      <!-- 步骤条 -->
      <el-steps
        :active="active - 0"
        finish-status="success"
        style="margin-top: 20px"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 表单 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addform"
        label-width="100px"
      >
        <keep-alive>
          <!-- 选项卡 -->
          <el-tabs
            tab-position="left"
            style="margin-top: 20px"
            v-model="active"
            :before-leave="beforeLeave"
            @tab-click="tabClick"
          >
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input
                  style="width: 60%"
                  v-model="addForm.goods_name"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input
                  type="number"
                  style="width: 60%"
                  v-model="addForm.goods_price"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input
                  type="number"
                  style="width: 60%"
                  v-model="addForm.goods_weight"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input
                  type="number"
                  style="width: 60%"
                  v-model="addForm.goods_number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <el-cascader
                  v-model="addForm.goods_cat"
                  :options="cateList"
                  :props="cateProps"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品参数" name="1">
              <el-alert
                title="无数据"
                v-if="attrs.length === 0"
                :closable="false"
                center
                type="warning"
              ></el-alert>
              <el-form-item
                :label="item.attr_name"
                prop="attrs"
                v-for="item in attrs"
                :key="item.attr_id"
                style="margin-top: 20px"
              >
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox
                    :label="attr"
                    border
                    v-for="attr in item.attr_vals"
                    :key="attr"
                  ></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品属性" name="2">
              <el-form-item
                v-for="item in onlyAttrs"
                :key="item.attr_id"
                :label="item.attr_name"
                label-width="150px"
              >
                <el-input
                  v-model="item.attr_vals"
                  size="small"
                  style="width: 50%"
                ></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <div v-if="editID" class="edit">
                <el-alert
                  title="暂不支持修改商品图片"
                  :closable="false"
                ></el-alert>
                <!-- 轮播图 -->
                <el-carousel
                  v-if="addForm.pics.length!==0"
                  :interval="4000"
                  style="margin-top: 20px; width: 80%"
                  height="500px"
                  type="card"
                >
                  <el-carousel-item
                    v-for="item in addForm.pics"
                    :key="item.pics_id"
                  >
                    <el-image
                      :src="item.pics_big_url"
                      style="width: 100%; height: 100%"
                    ></el-image>
                  </el-carousel-item>
                </el-carousel>
              </div>
              <el-upload
                v-else
                class="upload-demo"
                action="http://localhost:8888/api/private/v1/upload"
                :headers="{ Authorization: $store.state.token }"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :file-list="fileList"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
              <quillEditor
                v-model="addForm.goods_introduce"
                :options="editorOpt"
              />
              <el-button type="primary" style="margin-top: 20px" @click="add">{{
                editID ? "修改商品" : "添加商品"
              }}</el-button>
            </el-tab-pane>
          </el-tabs>
        </keep-alive>
      </el-form>
    </el-card>
    <!-- 图片预览弹出层 -->
    <el-dialog :visible.sync="showDialog" title="图片预览">
      <el-image style="width: 100%" :src="tempUrl"></el-image>
    </el-dialog>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css' // 富文本
import 'quill/dist/quill.snow.css' // 富文本
import 'quill/dist/quill.bubble.css' // 富文本
import { quillEditor } from 'vue-quill-editor' // 富文本
import {
  categories,
  attributes,
  addGoods,
  goodsDetail,
  editGoods
} from '@/api/goods'
import _cloneDeep from 'loadsh/cloneDeep'
export default {
  components: { quillEditor },
  data () {
    return {
      active: '0', // 当前步骤
      // 添加商品表单
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        attrs: [],
        pics: [],
        goods_introduce: ''
      },
      // 表单验证规则
      addRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      cateList: [], // 商品分类列表
      attrs: [], //  动态属性列表
      onlyAttrs: [], // 静态属性列表
      // 级联选择器配置
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      tempUrl: '', // 图片预览临时路径
      showDialog: false, // 展示/关闭 图片预览
      fileList: [],
      // 富文本配置
      editorOpt: {
        placeholder: '请输入商品介绍',
        modules: {
          toolbar: [
            [{ size: ['small', false, 'large'] }], // 字体大小
            ['blockquote', 'code-block'], // 引用 / 代码块
            ['bold', 'italic'], // 加粗 / 倾斜
            [{ header: 1 }, { header: 2 }], // 标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['link', 'image'], // 链接 / 图片(默认转base64)
            [{ color: [] }, { background: [] }], // 字体颜色 / 背景颜色
            [{ align: [] }] // 对齐方式
          ]
        }
      },
      editID: this.$route.query.goods_id || '' // 要修改商品的id
    }
  },
  async created () {
    this.categories()
    if (this.editID) {
      const res = await goodsDetail(this.editID)
      Object.keys(this.addForm).forEach((key) => {
        if (key === 'goods_cat') {
          this.addForm[key] = res[key].split(',').map((item) => item * 1)
        } else {
          this.addForm[key] = res[key]
        }
      })
    }
  },
  methods: {
    // 获取分类列表
    async categories () {
      const res = await categories()
      this.cateList = res
    },
    // 级联选择器简单校验(只能选择三级分类)
    handleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat.length = []
      }
    },
    // tab栏切换前钩子
    beforeLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.warning('请选择三级分类')
        return Promise.reject(new Error())
      }
    },
    // tab栏切换回调
    async tabClick () {
      if (this.active === '1') {
        try {
          const res = await attributes({
            id: this.addForm.goods_cat[2],
            sel: 'many'
          })
          res.forEach((item) => {
            item.attr_vals.length !== 0
              ? (item.attr_vals = item.attr_vals.split(' '))
              : (item.attr_vals = [])
          })
          this.attrs = res
        } catch (err) {
          console.log(err)
        }
      }
      if (this.active === '2') {
        try {
          const res = await attributes({
            id: this.addForm.goods_cat[2],
            sel: 'only'
          })
          this.onlyAttrs = res
        } catch (err) {
          console.log(err)
        }
      }
    },
    // 图片预览
    handlePreview (file) {
      this.tempUrl = file.url
      this.showDialog = true
    },
    // 删除图片
    handleRemove (file) {
      this.addForm.pics = this.addForm.pics.filter(
        (item) => item.temp_path !== file.tmp_path
      )
    },
    // 图片上传成功
    handleSuccess (res) {
      this.addForm.pics.push(res.data.temp_path)
    },
    // 添加商品按钮
    add () {
      this.$refs.addform.validate(async (isOk) => {
        if (!isOk) {
          return this.$message.error('请填写必要的表单项!')
        }
        const cloneForm = _cloneDeep(this.addForm)
        this.attrs.forEach((item) => {
          cloneForm.attrs.push({
            attr_id: item.attr_id,
            attr_vals: item.attr_vals.join(' ')
          })
        })
        this.onlyAttrs.forEach((item) => {
          cloneForm.attrs.push({
            attr_id: item.attr_id,
            attr_vals: item.attr_vals
          })
        })
        cloneForm.goods_cat = this.addForm.goods_cat.join(',')
        try {
          if (this.editID) {
            // 修改
            await editGoods({
              id: parseInt(this.editID),
              ...cloneForm
            })
            this.$message.success('修改成功')
          } else {
            // 添加
            await addGoods(cloneForm)
            this.$message.success('添加成功')
          }
          this.$router.push('/goods')
        } catch (err) {
          console.log(err)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  min-height: 80vh !important;
}
.container {
  padding: 20px;
  background-color: #f5f7f8;

  .el-checkbox {
    margin: 0 5px 0 0 !important;
  }
  ::v-deep .ql-editor {
    min-height: 300px !important;
  }
  ::v-deep .quill-editor {
    width: 80%;
  }
  .edit {
    display: flex;
    flex-flow: column;
    justify-content: center;
    align-items: center;
     background-color: rgba(204, 204, 204, 0.103);
    border-radius: 8px;
  }
}
</style>
